// 全局base 因为这个是html cdn的不得已
const BASE_PATH = "/前端权限控制/v1/index.html/";
// 默认路由
import home from "./home.js";
import welcome from "./welcome.js";
import login from "./login.js";
// 动态路由
import Users from "./users.js";
import Roles from "./roles.js";
import GoodsCate from "./categories.js";
import GoodsList from "./goods.js";

const Rule = {
  users: { path: "/users", component: Users },
  roles: { path: "/roles", component: Roles },
  goods: { path: "/goods", component: GoodsList },
  categories: { path: "/categories", component: GoodsCate },
};
const router = new VueRouter({
  mode: "hash",
  routes: [
    {
      path: "/",
      component: home,
      redirect: "/welcome",
      children: [{ path: "/welcome", component: welcome }],
    },
    {
      path: "/login",
      component: login,
      loading: {
        template: `<h3>加载中...</h3>`,
      },
      error: {
        template: `<h3>加载失败了,请重新加载</h3>`,
      },
      delay: 200,
      timeout: 3000,
    },
    {
      path: "*",
      component: {
        template: "<h3>您访问的地址丢失了哦</h3>",
      },
    },
  ],
});
// 这个只解决了用户登录访问的问题,要是用户登录完在地址里输入了这个用户不具权限的地址要动态路由处理了
router.beforeEach((to, from, next) => {
  // 如果是登录,就让它登录去
  if (to.path === "/login") {
    next();
  } else {
    // 如果其它地址,先看看有没有token
    const token = sessionStorage.getItem("jauthToken");
    // 没有token就让他去登录
    if (!token) {
      next("/login");
      // 有就跳转
    } else {
      next();
    }
  }
});
import store from './store.js'
// 根据请求过来的Vuex的数据建立mapping
const ruleMapping = {
  'users': Rule.users,
  'roles': Rule.roles,
  'goods': Rule.goods,
  'categories': Rule.categories
}
// 当前路由在刷新页面后,动态路由不复存在
export function initDynamicRoutes() {
  // 根据二级权限,对路由规则进行动态添加, 根据login登录时返回的数据 -> 到login.vue 去导入这个方法
  const currentRoutes = router.options.routes
  const rightList = store.state.rightList
  // 一级权限 one
  rightList.forEach((one) => {
    // 二级权限 two
    one.children.forEach(two => {
      // 根据请求过来的Vuex的数据建立mapping
      const temp = ruleMapping[two.path]
      temp.meta = two.rights
      currentRoutes[0].children.push(temp)
    })
  })
  console.log("currentRoutes", currentRoutes);
  // 更改好,调用这个方法,让我们更改的添加到路由生效
  router.addRoutes(currentRoutes)
}
export default router